package com.taotao.job.service.impl;

import com.google.common.base.Preconditions;
import com.taotao.job.dao.JobScheduleMetaMapper;
import com.taotao.job.model.entity.JobScheduleMeta;
import com.taotao.job.service.JobScheduleMetaService;
import com.taotao.job.util.EntityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 任务时间调度的元数据服务接口实现类
 * </p>
 *
 * @author Fan Beibei
 * @version V1.0
 * @since 2021-03-14 21:43:18
 */
@Slf4j
@Service
public class JobScheduleMetaServiceImpl implements JobScheduleMetaService {
    @Resource
    private JobScheduleMetaMapper jobScheduleMetaMapper;


    @Override
    public void softDelByIds(Set<java.lang.Long> ids, Long userId) {
        Preconditions.checkArgument(null != ids && ids.size() > 0);
        Preconditions.checkArgument(null != userId);

        jobScheduleMetaMapper.softDelByPks(ids, userId, new Date());
    }

    @Override
    public JobScheduleMeta queryById(java.lang.Long id) {
        Preconditions.checkArgument(null != id);

        return jobScheduleMetaMapper.selectByPk(id);
    }

    @Override
    public void addOrUpdate(JobScheduleMeta jobScheduleMeta, Long userId) {
        Preconditions.checkArgument(null != jobScheduleMeta);
        Preconditions.checkArgument(null != userId);

        if (null == jobScheduleMeta.getId()) {
            EntityUtils.setPo5Field(userId, new Date(), jobScheduleMeta);
            jobScheduleMetaMapper.insert(jobScheduleMeta);
        } else {
            EntityUtils.setPo2Field(userId, new Date(), jobScheduleMeta);
            //这里不做删除
            jobScheduleMeta.setIsDel(null);
            jobScheduleMetaMapper.updateByPk(jobScheduleMeta);
        }

    }

    @Override
    public List<JobScheduleMeta> getJobForSchedule(long timestamp) {
        Preconditions.checkArgument(timestamp > 0);

        return jobScheduleMetaMapper.selectJobForSchedule(timestamp);
    }

    @Override
    public void updateTriggerNextTime(Long jobId, long triggerNextTime) {
        Preconditions.checkArgument(null != jobId);
        Preconditions.checkArgument(triggerNextTime > 0);


        JobScheduleMeta j = new JobScheduleMeta();
        j.setId(jobId);
        j.setNextTriggerTime(triggerNextTime);
        j.setUpdateTime(new Date());
        jobScheduleMetaMapper.updateByPk(j);
    }


}
